/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.service.log.formoperate.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import yhao.infra.apilist.ValidationForm;
import yhao.infra.service.log.formoperate.LogInfo;
import yhao.infra.service.log.formoperate.LogUtil;
import yhao.infra.service.log.formoperate.annotation.FormOperateLog;

/**
 * form操作记录AOP
 *
 * @see LogUtil
 * @author yoara
 */
@Component
@Aspect
public class FormOperateAop {
    @Around(value = "@annotation(log)")
    public Object doLogProcess(ProceedingJoinPoint pjp, FormOperateLog log) throws Throwable {
        LogInfo info = makeLogInfo(pjp, log);
        Object result;
        try{
            result = pjp.proceed();
        }catch (Throwable t){
            info.setResult(t.getMessage());
            throw t;
        } finally {
            LogUtil.doLog(info);
        }
        return result;
    }

    private LogInfo makeLogInfo(ProceedingJoinPoint pjp, FormOperateLog log) {
        Object[] args = pjp.getArgs();
        LogInfo info = null;
        if(args!=null && args.length>0){
            for(Object arg:args){
                if(arg instanceof ValidationForm){
                    info = new LogInfo(pjp.getSignature().toShortString(),(ValidationForm)arg);
                    info.setDesc(log.desc());
                    break;
                }
            }
        }
        return info;
    }
}
